package com.rsstuan.parser;

import java.io.StringReader;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


import com.rsstuan.data.ArticleData;
import com.rsstuan.data.FeedOut;
import com.rsstuan.utils.ArticleUtils;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;

public class FeedParser {
	private  Logger LOG = Logger.getLogger(FeedParser.class.getName());
	
	public FeedOut parse(byte[] data) {
		try {
			SyndFeedInput input = new SyndFeedInput();
			FeedOut feedOut = new FeedOut();
			String str = new String(data);
			SyndFeed feed = input.build(new StringReader(str));
			
			feedOut.setFeed(feed);
			feedOut.setTitle(feed.getTitle());
			feedOut.setLink(feed.getLink());
			feedOut.setAuthor(feed.getAuthor());
			feedOut.setUri(feed.getUri());
			feedOut.setPubDate(feed.getPublishedDate());
			
			List entries = feed.getEntries();
			for (int i = 0; i < entries.size(); i ++) {
				SyndEntryImpl entry = (SyndEntryImpl)entries.get(i);
				ArticleData article = new ArticleData();
				article.setTitle(entry.getTitle());
				article.setAuthor(entry.getAuthor());
				article.setLink(entry.getLink());
				article.setDescription(entry.getDescription().getValue());
				article.setDigest(ArticleUtils.generateMd5Digest(entry.getDescription().getValue().getBytes()));
				article.setPubDate(entry.getPublishedDate());		
				feedOut.getArticles().add(article);		
			}			
			return feedOut;
		}
		catch (Exception e) {
			LOG.log(Level.WARNING, "feed parse failed", e);
			return null;
		}
		
		
	}

}
